package com.daffodil.storage.exception;

import java.util.Locale;

import org.springframework.context.MessageSource;
import org.springframework.context.NoSuchMessageException;
import org.springframework.context.i18n.LocaleContextHolder;

import com.daffodil.storage.util.SpringBeanUtils;


/**
 * -自定义基础异常
 * @author yweijian
 * @date 2022年12月13日
 * @version 2.0.0
 * @description
 */
public class BaseException extends RuntimeException {

    private static final long serialVersionUID = 1L;
    
    private static final String UNKNOWN_EXCEPTION = "Unknown exception";
    
    /** 业务异常代码 */
    protected int code;
    
    /** 业务异常消息 */
    protected String message;
    
    public BaseException() {
        super();
        this.code = 500;
        this.message = UNKNOWN_EXCEPTION;
    }

    public BaseException(String message) {
        this.code = 500;
        this.message = message;
    }
    
    public BaseException(int code) {
        this.code = code;
        this.message = this.getMessage(this.code);
    }
    
    public BaseException(int code, Object... args) {
        this.code = code;
        this.message = this.getMessage(this.code, args);
    }
    
    public int getCode() {
        return code;
    }

    public String getMessage() {
        return message;
    }

    /**
     * -获取异常
     * @param code
     * @param args
     * @return
     */
    private String getMessage(int code, Object... args) {
        MessageSource source = SpringBeanUtils.getBean(MessageSource.class);
        Locale locale = LocaleContextHolder.getLocale();
        Locale.setDefault(Locale.SIMPLIFIED_CHINESE);
        try {
            return source.getMessage(String.valueOf(code), args, locale);
        }catch (NoSuchMessageException e) {
            return UNKNOWN_EXCEPTION;
        }
    }

}